<template>
    <div>
        {{ company.id? '修改机构' : '添加机构'}}
    </div>
    <el-card>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            :size="formSize" status-icon>
            <div class="Basic_information">
                <p>基础信息</p>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="机构名称" prop="name">
                            <el-input v-model="ruleForm.name" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="选择省份" prop="city">
                            <el-cascader :options="citys" placeholder="选择城市" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">

                        <el-form-item label="地址" prop="address">
                            <el-input v-model="ruleForm.address" />
                        </el-form-item>

                    </el-col>


                    <el-col :span="12">

                        <el-form-item label="对外服务电话" prop="telephone">
                            <el-input v-model="ruleForm.telephone" />
                        </el-form-item>

                    </el-col>
                </el-row>


                <el-row>
                    <el-col :span="12">

                        <el-form-item label="管理员姓名" prop="adminUserName">
                            <el-input v-model="ruleForm.adminName" />
                        </el-form-item>

                    </el-col>


                    <el-col :span="12">

                        <el-form-item label="联系方式" prop="adminMobile">
                            <el-input v-model="ruleForm.adminMobile" />
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">

                        <el-form-item label="管理员账号" prop="adminName">
                            <el-input v-model="ruleForm.adminUserName" />
                        </el-form-item>

                    </el-col>


                    <el-col :span="12">

                        <el-form-item label="密码" prop="adminPwd">
                            <el-input v-model="ruleForm.adminPwd" />
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">

                        <el-form-item label="开业时间" prop="startTime">
                            <el-date-picker v-model="value1" type="datetime" placeholder="请选择开业时间" />
                        </el-form-item>

                    </el-col>
                </el-row>

            </div>
            <div class="Operate">
                <p>经营信息</p>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="法人代表" prop="legalPerson">
                            <el-input v-model="ruleForm.legalPerson" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="法人代表联系号码" prop="mobile">
                            <el-input v-model="ruleForm.mobile" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="统一社会信用代码" prop="creditCode">
                            <el-input v-model="ruleForm.creditCode" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="卫生许可证" prop="license">
                            <el-radio-group v-model="ruleForm.license">
                                <el-radio :value=1>是</el-radio>
                                <el-radio :value=0>否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否具备医疗定点资格:" prop="medicalPoint">
                            <el-radio-group v-model="ruleForm.medicalPoint">
                                <el-radio :value=1>是否具备</el-radio>
                                <el-radio :value=0>否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="房屋性质:" prop="house">
                            <el-radio-group v-model="ruleForm.house">
                                <el-radio :value="1">自有产权</el-radio>
                                <el-radio :value="2">租聘</el-radio>
                                <el-radio :value="3">合作使用</el-radio>
                                <el-radio :value="4">其他</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="营业执照">
                            <el-upload class="avatar-uploader" :action="uploadURL" :show-file-list="false"
                                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="上传图片">
                            <el-upload v-model:file-list="fileList" class="upload-demo" :action="uploadURL"
                                :on-preview="handlePreviews" :on-success="handleSuccessmore" :on-remove="handleRemoves"
                                list-type="picture">
                                <el-button type="primary">上传图片</el-button>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        图片格式为jig或png，大小不超过500kb
                                    </div>
                                </template>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="20">
                    </el-col>
                    <el-col :span="4">
                        <el-form-item class="btn">
                            <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                            <el-button>取消</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>

            </div>
        </el-form>
    </el-card>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, type ComponentSize, type FormInstance, type FormRules, type UploadProps, type UploadUserFile } from 'element-plus'
import { addAccount, getCity } from '@/apis/company/company';
import type { cityData, Company } from '@/apis/company/type';
import router from '@/router';
import { doEncrypt } from '@/utils/cryptoUtil';
import { useRoute } from 'vue-router';
let uploadURL: string = import.meta.env.VITE_BASE_URL + '/upload/add'

const route = useRoute();

const company=ref<Company>({
  id:route.params.id ? Number(route.params.id) :0,
  name:""
})
console.log(company.value.id);



interface RuleForm {
    address: string
    adminMobile: string
    adminName: string
    adminPwd: string
    adminUserName: string
    certificate: string
    city: string
    creditCode: string
    house: string
    id?: number
    legalPerson: string
    license?: number
    medicalPoint?: number
    mobile: string
    name: string
    picture: string
    province: string
    startTime: string
    telephone: string
}
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    name: '',
    province: '',
    city: '',
    address: '',
    license: 0,
    medicalPoint: 0,
    house: '1',
    certificate: '',
    picture: '',
    adminUserName: '',
    adminPwd: '',
    adminName: '',
    adminMobile: '',
    creditCode: '',
    legalPerson: '',
    mobile: '',
    startTime: '',
    telephone: ''
})

const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '机构名称', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    province: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '地址', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    telephone: [
        { required: true, message: '对外服务电话', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    adminUserName: [
        { required: true, message: '管理员姓名', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    adminMobile: [
        { required: true, message: '管理员联系方式', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    adminName: [
        { required: true, message: '管理员账号', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    adminPwd: [
        { required: true, message: '密码', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    legalPerson: [
        { required: true, message: '法人', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    mobile: [
        { required: true, message: '电话', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    creditCode: [
        { required: true, message: '社会信用代码', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    // city: [
    //     { required: true, message: '选择城市', trigger: 'blur' },
    //     // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    // ]
})

/**
 * 提交表单函数
 * @param {FormInstance | undefined} formEl - 表单实例，用于执行表单验证
 */
const submitForm = (formEl: FormInstance | undefined) => {

    ruleForm.startTime = value1.value

    console.log('添加表单', ruleForm);


    // 检查表单实例是否存在，如果不存在则直接返回
    if (!formEl) return
    // 调用表单实例的验证方法，验证表单数据是否有效
    formEl.validate(async (valid) => {
        // 如果表单数据验证通过
        if (valid) {
            console.log("验证通过");
            // 加密密码
            ruleForm.adminPwd = await doEncrypt(ruleForm.adminPwd);
            // 添加表单
            const res = await addAccount(ruleForm)
            //   跳转成功路由
            if (res) {
                router.push("/home")
            }
            console.log("添加成功", res);
        }
    })
}

// 开业时间存储
const value1 = ref('')

const radio = ref(3)


// 获取城市
interface City {
    value: string;
    label: string;
    children: { value: string; label: string; }[]

}
let options: cityData[] = []
let citys = ref<City[]>([])
const getCityLIst = async () => {
    let res = await getCity()
    // console.log('城市', res);
    // 确保 res 是数组类型，并进行类型断言
    if (Array.isArray(res)) {
        options = res as cityData[];
        // console.log(options);
        options.forEach(item => {
            citys.value.push({
                value: item.n,
                label: item.n,
                children: item.c.map(city => ({
                    value: city.n,
                    label: city.n
                }))
            })
        })
        // console.log('循环', citys);
    } else {
        console.error("返回数据不是数组类型", res);
        options = []; // 如果不是数组，初始化为空数组避免错误
    }
}
getCityLIst()

//////////////////////////////////////
// 营业执照上传
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // 创建并设置头像图片的URL
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    // console.log('图片上传成功', response, uploadFile);
    ruleForm.certificate = uploadFile.url as string
    // console.log(ruleForm);
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 检查图片格式是否为JPG
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片格式问 jpg 或 png !')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        // 检查图片大小是否超过2MB
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }


    return true
}


///
// 图片上传
const fileList = ref<UploadUserFile[]>([

])

// 处理移除文件的操作
const handleRemoves: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    // console.log('删除',uploadFile, uploadFiles)
    // console.log('删除数组',fileList.value);

    fileList.value = uploadFiles.filter(item => item.uid !== uploadFile.uid)
    let pictureStr: string = ''

    fileList.value.map(item => {
        pictureStr += item.url + ','
    })
    ruleForm.picture = pictureStr
    // console.log('图片上传',pictureStr);
    console.log(ruleForm);
}
// 处理预览操作的函数
const handlePreviews: UploadProps['onPreview'] = (file) => {
    console.log(file)
}



// 文件上传成功时的钩子
const handleSuccessmore: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    // 打印上传响应数据、上传的文件和所有上传文件列表
    // console.log(response, uploadFile, uploadFiles)

    console.log('图片上传', fileList.value);

    let pictureStr: string = ''

    fileList.value.map(item => {
        pictureStr += item.url + ','
    })
    ruleForm.picture = pictureStr
    // console.log('图片上传',pictureStr);
    console.log(ruleForm);


}



</script>

<style scoped lang='less'>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}


.Basic_information {
    width: 100%;
    // background-color: red;
}

// .btn{

//     background-color: red;
//     display: flex;
//     justify-content: end;
// }

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>